package org.linlinjava.litemall.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.linlinjava.litemall.admin.beans.dto.LumiereLevelCouponDto;
import org.linlinjava.litemall.admin.beans.dto.LumiereLevelMemberDto;
import org.linlinjava.litemall.admin.beans.dto.LumierePayMemberDto;
import org.linlinjava.litemall.admin.beans.vo.*;
import org.linlinjava.litemall.core.storage.config.StorageProperties;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.beans.Constants;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理卢米埃成员服务水平
 *
 * @author yliyun
 * @date 2022/09/14
 */
@Service
public class AdminLumiereLevelMemberService {
    /**
     * lumierel级别会员服务
     */
    @Autowired
    private LumierelLevelMemberService lumierelLevelMemberService;

    /**
     * litemall用户服务
     */
    @Autowired
    private LitemallUserService litemallUserService;

    /**
     * 卢米埃成员福利优惠服务
     */
    @Autowired
    private LumiereMemberWelfareCouponService lumiereMemberWelfareCouponService;

    /**
     * 卢米埃成员福利订阅服务
     */
    @Autowired
    private LumiereMemberWelfareSubscribeService lumiereMemberWelfareSubscribeService;

    /**
     * 卢米埃订阅规则服务
     */
    @Autowired
    private LumiereSubscribeRuleService lumiereSubscribeRuleService;


    /**
     * 添加
     *
     * @param dto dto
     * @return {@link Object}
     */
    public Object add(LumiereLevelMemberDto dto) {

        LumiereLevelMember member = new LumiereLevelMember();

        List<LumiereLevelMember> ms = lumierelLevelMemberService.findByName(dto.getName());

        if(ms.size() > 0){
            return ResponseUtil.fail(111,"该会员名称已存在");
        }

        //优惠券
        List<LumiereLevelCouponDto> coupons = dto.getCouponDtos();

        List<LumiereMemberWelfareCoupon> welfareCoupons = new ArrayList<>();
        if(coupons != null && coupons.size() > 0){
            coupons.stream().forEach(coupon -> {
                LumiereMemberWelfareCoupon welfareCoupon = new LumiereMemberWelfareCoupon();
                BeanUtils.copyProperties(coupon, welfareCoupon);
                welfareCoupon.setNumbers(coupon.getNumber());
                welfareCoupon.setMemberTypes((byte) 1);
                welfareCoupon.setAddTime(LocalDateTime.now());
                welfareCoupon.setUpdateTime(LocalDateTime.now());
                welfareCoupon.setDeleted(false);
                welfareCoupons.add(welfareCoupon);
            });
        }


        //订阅
        List<MemberSubscribeVo> subscribeVos = dto.getSubscribeVos();
        List<LumiereMemberWelfareSubscribe> welfareSubscribes = new ArrayList<>();

        if(subscribeVos != null && subscribeVos.size() >0){
            for (int i = 0; i < subscribeVos.size(); i++) {
                Integer[]  ruleIds = subscribeVos.get(i).getSubscribeRuleIds();
                for (int j = 0; j < ruleIds.length; j++) {
                    LumiereSubscribeRule rule = lumiereSubscribeRuleService.queryBySubscibeAndRuleId(subscribeVos.get(i).getSubscribeId(),ruleIds[j]);

                    if (rule == null) {
                        return ResponseUtil.fail(111, "订阅规则不存在");
                    }
                }

                LumiereMemberWelfareSubscribe welfareSubscribe = new LumiereMemberWelfareSubscribe();
                welfareSubscribe.setMemberTypes((byte) 1);
                welfareSubscribe.setSubscribeRuleIds(ruleIds);
                welfareSubscribe.setSubscribeId(subscribeVos.get(i).getSubscribeId());
                welfareSubscribe.setAddTime(LocalDateTime.now());
                welfareSubscribe.setUpdateTime(LocalDateTime.now());
                welfareSubscribe.setDeleted(false);
                welfareSubscribes.add(welfareSubscribe);
            }
        }

        //新增等级会员
        BeanUtils.copyProperties(dto, member);
        member.setStatus((byte) 1);
        member.setAddTime(LocalDateTime.now());
        member.setUpdateTime(LocalDateTime.now());
        member.setDeleted(false);

        //如果还没有一个等级会员,默认第一个等级会员的pid为null
        List<LumiereLevelMember> members = lumierelLevelMemberService.list(new LumiereLevelMemberExample());

        if(members.size() == 0){
            member.setPid(null);
        }


        lumierelLevelMemberService.add(member);

        welfareCoupons.stream().forEach(coupon -> {
            coupon.setMemberId(member.getId());
            lumiereMemberWelfareCouponService.add(coupon);
        });

        welfareSubscribes.stream().forEach(subscribe -> {
            subscribe.setMemberId(member.getId());
            lumiereMemberWelfareSubscribeService.add(subscribe);
        });

        return ResponseUtil.ok("添加等级会员成功");
    }

    /**
     * 细节
     *
     * @param memberId 成员身份
     * @return {@link Object}
     */
    public Object detail(Integer memberId){


         LumiereLevelMember levelMember = lumierelLevelMemberService.findById(memberId);
        LevelMemberVo vo = new LevelMemberVo();
        BeanUtils.copyProperties(levelMember,vo);
         //查询优惠券
        List<LumiereMemberWelfareCoupon> coupons =  lumiereMemberWelfareCouponService.findByMemberId(memberId,(byte)1);
        List<LumiereLevelCouponDto> couponDtos = new ArrayList<>();
        for (int i = 0; i < coupons.size(); i++) {
            LumiereLevelCouponDto couponDto = new LumiereLevelCouponDto();
            couponDto.setCouponId(coupons.get(i).getCouponId());
            couponDto.setCycleType(coupons.get(i).getCycleType());
            couponDto.setNumber(coupons.get(i).getNumbers());
            couponDtos.add(couponDto);
        }
        vo.setCouponDtos(couponDtos);
        if(levelMember.getPid() != null){
            LumiereLevelMember lastMember =  lumierelLevelMemberService.findById(levelMember.getPid());
            vo.setPName(lastMember.getName());
        }
        vo.setPid(levelMember.getPid());

        //订阅
        List<LumiereMemberWelfareSubscribe> welfareSubscribes =  lumiereMemberWelfareSubscribeService.findByMemberId(memberId,(byte)1);

        List<MemberSubscribeVo> subscribeVos  = welfareSubscribes.stream().map( subscribe -> {
            MemberSubscribeVo v = new MemberSubscribeVo();
            v.setSubscribeId(subscribe.getSubscribeId());
            v.setSubscribeRuleIds(subscribe.getSubscribeRuleIds());
            return v;
        }).collect(Collectors.toList());


        vo.setSubscribeVos(subscribeVos);

        vo.setGiftCardVos(new ArrayList<MemberGiftCardVo>());

        return ResponseUtil.ok(vo);
    }

    /**
     * 更新
     *
     * @param dto dto
     * @return {@link Object}
     */
    public Object update(LumiereLevelMemberDto dto) {

        if (dto.getId() == null) {
            return ResponseUtil.fail(222, "等级会员Id不能为空");
        }

        LumiereLevelMember lumiereLevelMember = lumierelLevelMemberService.findById(dto.getId());

        if (lumiereLevelMember == null) {
            return ResponseUtil.fail(333, "等级会员不存在");
        }

        LumiereLevelMember member = lumierelLevelMemberService.findById(dto.getId());

        //优惠券
        List<LumiereLevelCouponDto> coupons = dto.getCouponDtos();

        List<LumiereMemberWelfareCoupon> welfareCoupons = new ArrayList<>();
        if(coupons != null &&  coupons.size() > 0){
            coupons.stream().forEach(coupon -> {
                LumiereMemberWelfareCoupon welfareCoupon = new LumiereMemberWelfareCoupon();
                BeanUtils.copyProperties(coupon, welfareCoupon);
                welfareCoupon.setNumbers(coupon.getNumber());
                welfareCoupon.setMemberTypes((byte) 1);
                welfareCoupon.setAddTime(LocalDateTime.now());
                welfareCoupon.setUpdateTime(LocalDateTime.now());
                welfareCoupon.setDeleted(false);
                welfareCoupons.add(welfareCoupon);
            });
        }


        //订阅
        List<MemberSubscribeVo> subscribeVos = dto.getSubscribeVos();
        List<LumiereMemberWelfareSubscribe> welfareSubscribes = new ArrayList<>();

        if(subscribeVos != null && subscribeVos.size() >0){
            for (int i = 0; i < subscribeVos.size(); i++) {
                Integer[]  ruleIds = subscribeVos.get(i).getSubscribeRuleIds();
                for (int j = 0; j < ruleIds.length; j++) {
                    LumiereSubscribeRule rule = lumiereSubscribeRuleService.queryBySubscibeAndRuleId(subscribeVos.get(i).getSubscribeId(),ruleIds[j]);

                    if (rule == null) {
                        return ResponseUtil.fail(111, "订阅规则不存在");
                    }
                }

                LumiereMemberWelfareSubscribe welfareSubscribe = new LumiereMemberWelfareSubscribe();
                welfareSubscribe.setMemberTypes((byte) 1);
                welfareSubscribe.setSubscribeRuleIds(ruleIds);
                welfareSubscribe.setSubscribeId(subscribeVos.get(i).getSubscribeId());
                welfareSubscribe.setAddTime(LocalDateTime.now());
                welfareSubscribe.setUpdateTime(LocalDateTime.now());
                welfareSubscribe.setDeleted(false);
                welfareSubscribes.add(welfareSubscribe);
            }
        }


        //修改等级会员
        BeanUtils.copyProperties(dto, member);

        lumierelLevelMemberService.update(member);

        //删除优惠券相关
        LumiereMemberWelfareCouponExample example = new LumiereMemberWelfareCouponExample();
        example.or().andMemberIdEqualTo(dto.getId());
        lumiereMemberWelfareCouponService.deleteByExample(example);

        welfareCoupons.stream().forEach(coupon -> {
            coupon.setMemberId(member.getId());
            lumiereMemberWelfareCouponService.add(coupon);

        });

        //删除订阅相关
        LumiereMemberWelfareSubscribeExample ex = new LumiereMemberWelfareSubscribeExample();
        ex.or().andMemberIdEqualTo(dto.getId());
        lumiereMemberWelfareSubscribeService.deleteByExample(ex);

        welfareSubscribes.stream().forEach(subscribe -> {
            subscribe.setMemberId(member.getId());
            lumiereMemberWelfareSubscribeService.add(subscribe);
        });

        return ResponseUtil.ok("修改等级会员成功");
    }

    /**
     * 删除
     *
     * @param memberId 成员身份
     * @return {@link Object}
     */
    public Object delete(Integer memberId) {
        List<LitemallUser> users = listUserByLevelMemberId(memberId);

        if(users.size() > 0){
            return ResponseUtil.fail(111,"已存在用户拥有该会员,不能删除");
        }

        lumierelLevelMemberService.delete(memberId);
        return ResponseUtil.ok("删除等级会员成功");
    }

    /**
     * 列表
     *
     * @param levelMemberName 级成员名
     * @param page            页面
     * @param limit           限制
     * @param sort            排序
     * @param order           订单
     * @return {@link Object}
     */
    public Object list(String levelMemberName, Integer page, Integer limit,
                       String sort, String order) {

        LambdaQueryWrapper<LumiereLevelMember> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(levelMemberName != null,LumiereLevelMember::getName,levelMemberName);
        lambdaQueryWrapper.eq(LumiereLevelMember::getDeleted,false);
        lambdaQueryWrapper.orderByDesc(LumiereLevelMember::getAddTime);

        IPage<LumiereLevelMember> list = lumierelLevelMemberService.page(new Page(page, limit), lambdaQueryWrapper);
        // 提前获取所有用户数量，避免在每次循环中都查询
        Integer allUser = litemallUserService.queryAll().size();

        // 创建 DecimalFormat 只需一次
        DecimalFormat decimalFormat = new DecimalFormat("##.00%");

        List<LumiereLevelMemberVo> vos = new ArrayList<>();
        for (LumiereLevelMember member : list.getRecords()) {
            LumiereLevelMemberVo vo = new LumiereLevelMemberVo();

            // 直接赋值属性，减少BeanUtils的使用
            vo.setId(member.getId());
            vo.setName(member.getName());
            vo.setAddTime(member.getAddTime().toString());
            vo.setPid(member.getPid());

            // 查询该会员持有的人数
            Integer count = litemallUserService.queryUserByLevelMemberId(member.getId()).size();
            vo.setNumbers(count);

            // 计算比例
            double ratio = count * 1.0 / allUser;
            vo.setPer(decimalFormat.format(ratio));

            // 设置 isDefault
            vo.setIsDefault((byte) (member.getPid() == null ? 1 : 0));

            // 如果有父级，查询父级名称
            if (member.getPid() != null) {
                LumiereLevelMember lastMember = lumierelLevelMemberService.findById(member.getPid());
                vo.setPName(lastMember.getName());
            }

            vos.add(vo);
        }

        return ResponseUtil.okPage(list,vos);
    }

    /**
     * 查询会员没有孩子
     *
     * @return {@link Object}
     */
    public Object queryMemberNoChildren() {
        LumiereLevelMemberExample example = new LumiereLevelMemberExample();
        example.or().andDeletedEqualTo(false);

        List<LumiereLevelMember> lumiereLevelMembers = lumierelLevelMemberService.list(example);

        List<LumiereLevelMember> list = lumiereLevelMembers.stream().sorted(Comparator.comparing(LumiereLevelMember::getId).reversed()).collect(Collectors.toList());
        List<LumiereLevelMember> members = new ArrayList<LumiereLevelMember>();
        members.add(list.get(0));
        return ResponseUtil.okList(members);
    }

    /**
     * 更新状态
     *
     * @param memberId 成员身份
     * @return {@link Object}
     */
    public Object updateStatus(Integer memberId) {

        LumiereLevelMember member = lumierelLevelMemberService.findById(memberId);

        if (member == null || member.getDeleted() == true) {
            return ResponseUtil.fail(111, "会员不存在,不能修改状态");
        }

        member.setId(memberId);
        if (member.getStatus() == Constants.MEMBER_STATUS_ADD) {
            member.setStatus(Constants.MEMBER_STATUS_INUSE);
        } else if (member.getStatus() == Constants.MEMBER_STATUS_INUSE) {
            member.setStatus(Constants.MEMBER_STATUS_NOUSE);
        } else if (member.getStatus() == Constants.MEMBER_STATUS_NOUSE) {
            member.setStatus(Constants.MEMBER_STATUS_INUSE);
        }
        lumierelLevelMemberService.update(member);
        return ResponseUtil.ok("更新会员状态成功");
    }

    /**
     * 用户级别会员id列表
     *
     * @param memberId 成员身份
     * @return {@link List}<{@link LitemallUser}>
     */
    public List<LitemallUser> listUserByLevelMemberId(Integer memberId){
        LitemallUserExample example = new LitemallUserExample();
        example.or().andLevelMemberIdEqualTo(memberId);

        return litemallUserService.queryUserByLevelMemberId(memberId);
    }

}
